<template>
  <div class="app-container">
    <!--查询条件-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="任务号" prop="docNum">
            <el-input
              v-model="queryParams.docNum"
              placeholder="请输入任务号模糊查询"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="queryParams.dtDocStart"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="起始日期"
              end-placeholder="截止日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="queryParams.dtDocFinish"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="起始日期"
              end-placeholder="截止日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
    </el-form>
    <!--批量删除按钮-->
    <el-row :gutter="10" class="mb8">
        <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:tasks:add']"
        >新增
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:tasks:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:tasks:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:tasks:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--生产任务列表-->
    <el-table v-loading="loading" stripe :data="tasksList" :highlight-current-row="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" fixed="left"/>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
            <span>{{ props.row.confirmNickName }}</span>
          </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="投放时间" align="center" prop="docDt" width="150"/>
      <el-table-column label="任务号" align="center" prop="docNum" width="150"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="物料编码" align="center" prop="itemNum" width="160"/>
      <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
      <el-table-column label="数量" align="center" prop="taskQty" width="100"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="docDtStart" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docDtStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="docDtEnd" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.docDtEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划订单号" align="center" prop="planDocNum" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="show_erpPs(scope.row)"
          >{{scope.row.planDocNum}}<i class="el-icon-caret-right"></i>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="投放人" align="center" prop="taskNickName" width="100"/>

      <el-table-column label="车间" align="center" prop="deptName" width="120"/>
      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="已完成" align="center" prop="sysYesNoDone" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoDone"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:tasks:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:tasks:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">删除
          </el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['com:dropdown:more']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="showDialog_confirm" icon="el-icon-success"
                                v-hasPermi="['oa:confirm:edit']"
                                :disabled="scope.row.oaDictConfirmStatus !='waiting'">审核</el-dropdown-item>
              <el-dropdown-item command="setDone" icon="el-icon-s-flag"
                                v-hasPermi="['com:single:done']">完成</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>


        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改生产任务管理对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="700px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                  style="margin-bottom: 15px;"
                  :title="form.latestTaskInfo"
                  type="info"
                  :closable="false"
                  effect="dark"
        >
        </el-alert>
          <el-input v-model="form.fkMesProcessUuid " v-show="false"/>
        <el-row>
          <el-form-item label="计划订单" prop="fkErpPsUuid">
            <el-input v-model="form.fkErpPsUuid"  v-show="false"/>
            <el-input placeholder="请点击右侧按钮选择计划订单"
                      v-model="form.selectedErpPs"
                      class="input-with-select"
                      :style="{width: '100%'}"

                      readOnly="true"
            >
              <el-button type="info" plain
                         @click="dialog_show_selectErpPs"
                         slot="append"
                         icon="el-icon-search" ></el-button>
            </el-input>
          </el-form-item>


          <el-col :span="12">

            <el-form-item label="任务号" prop="docNum">
              <el-input v-model="form.docNum" placeholder="请输入任务号"/>
            </el-form-item>


            <el-form-item label="物料名称">
              <span>{{ this.form.itemName }}</span>
            </el-form-item>



            <el-form-item label="物料规格">
              <span>{{ this.form.wmsDictMeasuringUnit }}</span>
            </el-form-item>

            <el-form-item label="开始时间" prop="docDtStart">
              <el-date-picker clearable size="small"
                              v-model="form.docDtStart"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择开始时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="投放时间" prop="docDt">
              <el-date-picker clearable size="small"
                              v-model="form.docDt"
                              type="datetime"
                              placeholder="选择结束时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">

            <el-form-item label="车间" prop="fkDeptId">
              <el-select
                filterable
                v-model="form.fkDeptId"
                placeholder="请选择车间"
                clearable
                size="small"
                :style="{width: '100%'}">
                <el-option
                  v-for="item in deptList"
                  :key="item.fkDeptId"
                  :label="item.deptName"
                  :value="item.fkDeptId"
                />
              </el-select>
            </el-form-item>


            <el-form-item label="物料编码">
              <span>{{ this.form.itemNum }}</span>
            </el-form-item>

            <el-form-item prop="taskQty">
            <span slot="label">
                    数量
                   <el-tooltip content="计划投放数量" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
              <el-input v-model="form.taskQty" placeholder="请输入数量"/>
            </el-form-item>


            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form.selectedAttentionUser" class="input-with-select">
                <el-button @click="showDialog_selectTaskAttentionUserName(form)" :style="{width: '100%'}" slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>

            <el-form-item label="结束时间" prop="docDtEnd">
              <el-date-picker clearable size="small"
                              v-model="form.docDtEnd"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择结束时间"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>

          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form.docNote" placeholder="请输入备注" :style="{width: '100%'}" type="textarea"
                        autosize/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--组件-->
    <select-mesPs ref="component_selectMesPs" @ok="selectMesPs_done"/>
    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done" />
    <select-erpPs ref="component_selectErpPs" @ok="selectErpPs_done" />
    <confirm ref="component_confirm" @ok="confirm_done()"/>
  </div>
</template>

<script>
  import {listTasks, getTasks, delTasks, addTasks, updateTasks} from "@/api/mes/tasks";
  import selectMesPs from "../../mes/ps/selectMesPs";
  import {newDocNum} from "@/api/oa/docNum";
  import selectErpPs from "../../erp/ps/selectErpPs";
  import selectUser from "../../comn/userGroup/selectUser";
  import confirm from "../../oa/confirm";
  import {  addPs } from "@/api/mes/ps";
  import {listDeptGroup} from "@/api/comn/deptGroup";
  import { parseTime } from '@/utils/ruoyi'

  export default {
    name: "Tasks",
    dicts: ['sys_yes_no', 'wms_dict_measuring_unit', 'sys_normal_disable',
      'mes_dict_quota_level', 'oa_dict_confirm_status'],
    components: {selectMesPs, selectUser, confirm,selectErpPs},
    data() {
      return {
        fold_ps_order: 'false',
        fold_process_exec_order: 'false',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 生产任务管理表格数据
        tasksList: [],
        deptList:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fkPsUuid: null,
          sysYesNoDone: null,
          taskQty: null,
          wmsDictMeasuringUnit: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDtStart: null,
          docDtEnd: null,
          docNote: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          fkErpPsUuid: [
            {required: true, message: "计划订单不能为空", trigger: "change"}
          ],
          fkDeptId: [
            {required: true, message: "车间不能为空", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "任务号不能为空", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人不能为空", trigger: "change"}
          ],
          docDtEnd: [
            {required: true, message: "结束时间不能为空", trigger: "change"}
          ],
          docDtStart: [
            {required: true, message: "开始时间不能为空", trigger: "change"}
          ],
          taskQty: [
            {required: true, message: "数量不能为空", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "投放时间不能为空", trigger: "change"}
          ],
          createBy: [
            {required: true, message: "创建者不能为空", trigger: "change"}
          ],
          createTime: [
            {required: true, message: "创建时间不能为空", trigger: "change"}
          ],
        }
      };
    },
    created() {

      // $route params
      let taskDocNum = this.$route.params && this.$route.params.taskDocNum;
      if (taskDocNum) {
        this.queryParams.docNum = taskDocNum
      }else console.log('！！！ 无参数 ！！！')


      this.getList();
      this.getList_dept()
    },
    methods: {
      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'mes_tasks',
          uuidColumn: 'task_uuid',
          fkUuid: row.taskUuid,
          attentionUserNickName: row.taskNickName,
          oaDictConfirmStatus: row.oaDictConfirmStatus,
          msg: `请审核车间任务, 任务号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);

      },

      confirm_done() {

        this.getList()

        this.genMepPs()
      },
      /** 查询生产任务管理列表 */
      getList() {
        this.loading = true;
        if (this.queryParams.dtDocStart) {
          this.queryParams.dtDocStartBegin = this.queryParams.dtDocStart[0]
          this.queryParams.dtDocStartEnd = this.queryParams.dtDocStart[1]
        } else {
          this.queryParams.dtDocStartBegin = null
          this.queryParams.dtDocStartEnd = null
        }
        if (this.queryParams.dtDocFinish) {
          this.queryParams.dtDocFinishBegin = this.queryParams.dtDocFinish[0]
          this.queryParams.dtDocFinishEnd = this.queryParams.dtDocFinish[1]
        } else {
          this.queryParams.dtDocFinishBegin = null
          this.queryParams.dtDocFinishEnd = null
        }
        listTasks(this.queryParams).then(response => {
          this.tasksList = response.rows;
          console.log(this.tasksList)
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 列表: 部门（车间） */
      getList_dept() {
        listDeptGroup({comnDictDeptGroup: 'workshop'}).then(response => {
          this.deptList = response.rows;
        });
      },
      genMepPs() {
        console.log(this.form)
        addPs(this.form).then(response => {
          this.open = false;
        });

      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          taskUuid: null,
          fkPsUuid: null,
          sysYesNoDone: null,
          taskQty: null,
          wmsDictMeasuringUnit: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDtStart: null,
          docDtEnd: null,
          docNote: null,
          fkErpPsUuid: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          fkAttentionUserId: null,
          selectedAttentionUser: null,
          fkConfirmUserId: null,
          selectedErpPs: null,
          confirmDt: null,
          oaDictConfirmStatus: "0",
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          selectedMesPs: null,
          taskNickName: null,
          processDocNum: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskUuid)
        this.docDts = selection.map(item => item.docDt)
        this.docNums = selection.map(item => item.docNum)
        this.single = selection.length !== 1
        this.oaDictConfirmStatus = selection.map(i => i.oaDictConfirmStatus)
        let editing = 'editing';
        this.multiple =
          (this.oaDictConfirmStatus.indexOf(editing) > -1 && [...new Set(this.oaDictConfirmStatus)] == editing) ? false : true
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.oaDictConfirmStatus = 'editing'

        newDocNum({preCode: 'TSK-', len: 12}).then(response => {
          this.form.docNum = response.msg
          console.log(this.form.docNum)
        })

        this.open = true;
        this.title = "添加车间任务管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const taskUuid = row.taskUuid || this.ids
        console.log(taskUuid)
        getTasks(taskUuid).then(response => {
          this.form = response.data;
          console.log(this.form)
          this.form.selectedAttentionUser = `${this.form.taskNickName}(${this.form.fkAttentionUserId})`
          this.form.selectedErpPs = `计划订单号：${this.form.planDocNum}`

          this.form.itemName = row.itemName
          this.form.itemNnum = row.itemNum
          this.form.wmsDictMeasuringUnit = this.selectDictLabel(this.dict.type.wms_dict_measuring_unit, row.wmsDictMeasuringUnit)

          this.form.oaDictConfirmStatus =
            ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
              ? 'editing' : this.form.oaDictConfirmStatus


          if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
            this.form.latestTaskInfo='💡 该条记录审核状态为'+
              this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
          }

          this.open = true;
          this.title = "修改生产任务";
        });
      },
      /** 提交按钮 */
      submitForm(confirmStatus) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            if (this.form.taskUuid != null) {
              updateTasks(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addTasks(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const taskUuids = row.taskUuid || this.ids;
        const docDts = row.docDt || this.docDts;
        const docNums = row.docNum || this.docNums;
        this.$modal.confirm('是否确认删除投放时间为"' + docDts + '",任务号为"' + docNums + '"的车间任务？', '删除确认').then(function () {
          return delTasks(taskUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('mes/tasks/export', {
          ...this.queryParams
        }, `mes_tasks.xlsx`)
      },
      /** 显示对话框：选择生产计划 */
      dialog_show_selectMesPs() {
        this.$refs.component_selectMesPs.dialog_show_selectMesPs();
      },

      /** 选择生产计划完成 */
      selectMesPs_done(plan) {
        this.form.fkPsUuid = plan.mesPsUuid
        console.log(this.form.fkPsUuid)
        console.log(plan)
        this.form.selectedMesPs =
          `开始时间：${plan.dtStart}，完成时间：${plan.dtFinish}`
        this.form.plan_docNum = plan.docNum
        this.form.plan_docDt = plan.dtStart
        this.form.done_docDt = plan.dtFinish
        this.form.o_itemName = plan.itemName
        this.form.o_itemNum = plan.itemNum
        this.form.plan_psQty = plan.psQty
        this.form.p_attentionUserName = plan.attentionUserName
        this.form.p_docNum = plan.processDocNum
        this.getList()
      },
      /** 选择经办人 */
      showDialog_selectTaskAttentionUserName( form ) {
        this.currentForm = form
        // this.$refs.component_selectAttentionUser.userGroup = 'worker';
        this.$refs.component_selectAttentionUser.show();
      },
      /** 选择经办人 - 完成 */
      selectAttentionUser_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.selectedAttentionUser = user.userNickNameAndId
      },


      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "showDialog_confirm":
            this.showDialog_confirm(row);
            break;
          case "setDone":
            let id = row.taskUuid

            this.$modal.confirm( `是否确认任务号为 ${row.docNum} 的车间任务单已完成？`, '完成确认').then(function() {
              let d = {
                taskUuid: id,
                sysYesNoDone: row.sysYesNoDone == 'Y' ? 'N':'Y'
              }

              return updateTasks(d).then(response => {
              });

            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }).catch(() => {});

            break;
          default:
            break;
        }
      },

      // 显示 - 总计划
      show_erpPs(r) {
        console.log(r)
        this.$router.push(`/erp/ps/docNum/${r.planDocNum}`);
      },

      /** 显示对话框：选择加工单 */
      dialog_show_selectErpPs() {
        this.$refs.component_selectErpPs.dialog_show_selectErpPs();
      },

      /** 选择生加工单完成 */
      selectErpPs_done(plan) {
        console.log(plan)
        this.form.fkMesProcessUuid = plan.fkMesProcessUuid
        this.form.fkErpPsUuid = plan.erpPsUuid
        this.form.selectedErpPs =
          `计划订单号：${plan.docNum}，计划时间：${plan.docDt}`
      },


    }
  };
</script>
